#include<stdio.h>
#include "../include/vfs.h"
#include<stdlib.h>
#include<string.h>


int copyfile( char src[], char dest[])
{
	int i,j,saveblock;
	long recsize;
	char *data;

	FILE *fp;
	FD *fd,*new,*destin,*destin1=NULL;
	Block *b;

	if((dest[strlen(dest)-1]=='/') && (strlen(dest)>2))
		dest[strlen(dest)-1]='\0';

	fd = malloc(sizeof(FD));
	strcpy(fd->path,src);

	destin = malloc(sizeof(FD));
	strcpy(destin->path,dest);

	b = malloc(sizeof(Block));

	fp = fopen(filesystem_name,"r+b");

	header=malloc(sizeof(Header));

	fread(header,sizeof(Header),1,fp);

	data = malloc(1024*sizeof(char));

	recsize=sizeof(Block);

	
		fd = search(roots.naryroot,fd);

		if(fd==NULL)
		{
			return 1;
		}

		if(fd->file_type==0)
			return 5;
		
		destin1 = search(roots.naryroot,destin);

		if(destin1==NULL)
			return 2;

		if(strcmp(src,"")==0)
			return 3;

		if(strcmp(dest,"")==0)
			return 4;

		if(destin1->file_type>0)
		{
			overwrite(destin,fd);

			return 0;

		}
			
		
		else
		{
			saveblock=fd->block_no;

		
			for(i=0;i<header->num_blocks;i++)
			{
				fread(b,sizeof(Block),1,fp);
			
				if (b->num==saveblock)					
				{
					strcpy(data,b->buffer);
					
					break;
				}
			}
		

		
				for(i=0;i<header->max_FD;i++)
				{
					if(header->fd_list[i].block_no==0)
					{
						new=(FD*)malloc(sizeof(FD));
						strcpy(new->filename,fd->filename);
						strcat(dest,"/");
						strcat(dest,fd->filename);
						strcpy(new->path,dest);
						new->file_type =2;
						new->file_size=strlen(data);
						break;
					}

				}

	
					for(j=0;j<header->num_blocks;j++)
					{
						if(header->freelist[j].isfree==1)
						{

							new->block_no=header->freelist[j].block;
							header->freelist[j].isfree=0;
							
							break;
						}
					}


					if(j==header->num_blocks)
						return 6;

					roots.naryroot=add_node(roots.naryroot,new,0);
					hashtable_insert(new);

					
			b=(Block*)malloc(sizeof(Block));
			strcpy(b->buffer,data);
			b->num = j+1;

			rewind(fp);
			fwrite(header,sizeof(Header),1,fp);
		
			fseek(fp,j*recsize,SEEK_CUR); 
			fwrite(b,sizeof(Block),1,fp);
	}

	fclose(fp);

	return 0;

}
